import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import zhCn from 'element-plus/es/locale/lang/zh-cn';

import {renderWithQiankun,  qiankunWindow} from 'vite-plugin-qiankun-xm/dist/helper'

let instance: any = null

const initQiankun = () => {
  renderWithQiankun({
    mount(props) {
      let container = null as unknown as HTMLElement
      const appContainer = document.getElementById('sub-app')
      if (appContainer) {
        container = appContainer
      } else {
        container = document.createElement('div')
        props.container?.appendChild(container)
      }
      render(container)
    },
    bootstrap() {
      console.log('bootstrap')
    },
    update() {
      console.log('update')
    },
    unmount() {
      console.log('unmount')
      if (instance) {
        instance.unmount()
      }
    }
  })
}

const render = async(container?: HTMLElement | undefined) => {
  const appDom = container ? container : '#sub-app'
  instance = createApp(App)
  instance
    .use(router)
    .use(ElementPlus, { locale: zhCn })
    .mount(appDom)
}

qiankunWindow.__POWERED_BY_QIANKUN__ ?  initQiankun() : render()
